<!--
 * @Author: your name
 * @Date: 2020-06-09 16:38:46
 * @LastEditTime: 2020-07-09 16:26:46
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \IM_Web\im_web\src\components\chatItem\chatItem.vue
--> 
<template>
    <div class="chat_item">
        <div v-if="msg.type === 'timeTag'" class="tip">
            <span>{{msg.showText}}</span>
        </div>
        <!-- <div
            v-else-if="msg.type==='notification' && msg.scene==='team'"
            class="tip"
        >{{msg.showText}}</div>-->
        <div v-else-if="msg.type==='tip'" class="tip">{{msg.tip}}</div>
        <!-- <div v-else-if="msg.type==='notification' && msg.scene==='team'" class="notification">{{msg.showText}}</div> -->
        <div v-else>
            <div
                class="flex justify_end"
                v-if="msg.flow ==='out'"
                @contextmenu.prevent="onContextmenu(msg)"
            >
                <div class="txt_info" style="background:#2396F7;color:#fff">
                    <div v-if="msg.type==='image'">
                        <img
                            :src="msg.originLink"
                            style="max-height:150px;max-width:200px;"
                            @click="imgPreview(msg.originLink)"
                        />
                    </div>
                    <div v-else-if="msg.type==='file'">
                        <!-- <img
                            :src="msg.fileLink"
                            v-if="msg.file.ext === 'jpg' || msg.file.ext === 'png' || msg.file.ext === 'jpeg' || msg.file.ext === 'gif'"
                            style="max-width:200px;max-height:150px;"
                            @click="imgPreview(msg.fileLink)"
                        />-->
                        <div @click="handleDownload(msg.content.ent[0].data)">
                            <!-- <a
                                :href="msg.fileLink+msg.file.name"
                                :download="msg.file.name"
                                target="_blank"
                                style="color:#fff;"
                            >-->
                            <Icon type="md-folder" style="font-size: 20px;" />
                            {{msg.showText}}
                            <!-- </a> -->
                        </div>
                    </div>
                    <div v-if="msg.type ==='text'" v-html="msg.showText"></div>
                    <div class="triangle triangle_right"></div>
                </div>
                <div
                    class="avatar avatar_right"
                    :style="{background:`url(${msg.avatar})`,backgroundSize:'100% 100%'}"
                ></div>
            </div>
            <div class="flex" v-else>
                <div
                    class="avatar"
                    :style="{background:`url(${msg.avatar})`,backgroundSize:'100% 100%'}"
                ></div>
                <div class>
                    <div
                        v-show="msg.scene ==='team'"
                        style="text-align:left;padding-left:12px;margin-bottom: 4px;margin-top:-10px;"
                    >{{msg.fromNick}}</div>
                    <div class="txt_info" style="min-height:40px;">
                        <div v-if="msg.type==='image'">
                            <img
                                :src="msg.originLink"
                                v-if="msg.type === 'image'"
                                style="max-width:150px;height:auto;"
                                @click="imgPreview(msg.originLink)"
                            />
                        </div>
                        <div v-else-if="msg.type==='file'">
                            <img
                                :src="msg.fileLink"
                                v-if="msg.type === 'image'"
                                style="max-height:150px;"
                                @click="imgPreview(msg.fileLink)"
                            />
                            <div v-else @click="handleDownload(msg.content.ent[0].data)">
                                <!-- <a
                                    :href="msg.fileLink"
                                    :download="msg.file.md5+msg.file.name"
                                    target="_blank"
                                >-->
                                <Icon type="md-folder" style="font-size: 20px;" />
                                {{msg.showText}}
                                <!-- </a> -->
                            </div>
                        </div>
                        <div v-if="msg.type ==='text'" v-html="msg.showText"></div>
                        <div class="triangle triangle_left"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import util from "../../utils";
import config from "../../configs";
import emojiObj from "../../configs/emoji";
import tea from "../../utils/TEA.js";
import axios from "axios";
import { Drafty } from "tinode-sdk";
// import state from "../../store/state";
// import download from "downloadjs";
// import download from "../../utils/dowload"
export default {
    props: {
        rawMsg: {
            type: Object,
            default() {
                return {};
            }
        },
        userInfos: {
            type: Object,
            default() {
                return {};
            }
        },
        myInfo: {
            type: Object,
            default() {
                return {};
            }
        }
    },
    data() {
        return {
            type: "session",
            msg: ""

            // isTeam: false
        };
    },
    computed: {},
    created() {
        // this.isTeam = /^team/.test(this.sessionId) ? true : false;
    },
    beforeMount() {
        this.computedItem();
    },
    mounted() {},
    watch: {
        rawMsg(newVal, oldVal) {
            console.log(newVal, oldVal);
            let newCustom = newVal && newVal.localCustom;
            if (!newCustom || !newVal || newVal.type !== "audio") {
                return;
            }
            let oldCustom = oldVal && oldVal.localCustom;
            console.log("newVal", newVal);
            console.log(oldVal);
            console.log(oldVal.localCustom);
            if (newCustom !== oldCustom) {
                this.computedItem();
            }
        }
    },
    methods: {
        onContextmenu(msg) {
            // let attrs = vNode.data.attrs
            let revocate = 60 * 2 * 1000;
            let nowTime = Number(new Date());
            if (nowTime - Number(new Date(msg.ts)) > revocate) {
                return false;
            }
            this.$contextmenu({
                items: [
                    {
                        label: "撤回",
                        onClick: () => {
                            nowTime = Number(new Date());
                            if (nowTime - Number(new Date(msg.ts)) > revocate) {
                                this.$Message.error(
                                    "只能撤回2分钟以内的消息！"
                                );
                                return false;
                            }
                            // this.message = "撤销";
                            // console.log("撤回");
                            this.$store.dispatch("revocateMsg", {
                                idClient: msg.idClient
                            });
                        }
                    }
                ],
                event,
                //x: event.clientX,
                //y: event.clientY,
                customClass: "class-a",
                zIndex: 3,
                minWidth: 80
            });
            return false;
        },
        // 下载按钮点击事件
        handleDownload(data) {
            // 下载附件
            // let nim = this.$store.state.nim;
            // var downloader = nim.getLargeFileHelper();
            // downloader
            //     .download(url, fileName, mime, loaded => {
            //         console.log(url, fileName, mime, loaded);
            //     })
            //     .then(() => {
            //         console.log("success");
            //     })
            //     .catch(err => {
            //         if (err) {
            //            this.$Message.error(
            //                 "Error downloading file: " + err.message,
            //                 "err"
            //             );
            //         }
            //     });
            console.log(data);
            console.log(Drafty.getDownloadUrl(data));
            console.log(Drafty.getEntityMimeType(data));
            console.log(Drafty.getEntitySize(data));
            console.log(Drafty.getContentType(data));
            console.log(Drafty.getPreviewUrl(data));
            // console.log(util.sanitizeUrl(data));
            let url = Drafty.getDownloadUrl(data);
            console.log(util.sanitizeUrl(url));
            let filename = data.name;
            let mimetype = Drafty.getEntityMimeType(data);
            let downloadUrl = Drafty.getPreviewUrl(data);
            console.log(downloadUrl);
            if (!downloadUrl) {
                url = "/v3" + url;
                try {
                    const nim = this.$store.state.nim; //Vuex  new() Tinode
                    var downloader = nim.getLargeFileHelper();
                    // downloader.download(Drafty.getDownloadUrl(data), filename, mimetype);
                    // const downloader = nim.getLargeFileHelper();
                    downloader
                        .download(Drafty.getDownloadUrl(data), filename, mimetype, loaded => {
                            console.log(loaded);
                        })
                        .then(() => {
                            // this.setState({ downloader: null, progress: 0 });
                        })
                        .catch(err => {
                            console.log(err.message);
                        });
                } catch (error) {
                    console.log(error)
                }
            }
            axios
                .get(url,{},{
                    responseType: "blob",
                    headers: {
                        "Content-Type":
                            "application/json;application/octet-stream"
                    }
                })
                .then(res => {
                    let blob = new Blob([res.data], { type: mimetype });
                    // 注: mime类型必须整正确, 否则下载的文件会损坏
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        // 兼容IE
                        // window.navigator.msSaveOrOpenBlob(
                        //     blob,
                        //     element.original_name
                        // );
                        console.log("IE");
                    } else {
                        let downloadElement = document.createElement("a");
                        downloadElement.href = window.URL.createObjectURL(blob); // 创建一个DOMString
                        downloadElement.download = filename;
                        downloadElement.click();
                        window.URL.revokeObjectURL(blob); // 释放 DOMString  ,解除内存占用
                    }
                })
                .catch(error => {
                    console.error(error);
                });
        },
        imgPreview(url) {
            console.log(url);
            this.$emit("previewImg", url);
        },
        computedItem() {
            let item = Object.assign({}, this.rawMsg);
            // console.log("item", item);
            // 标记用户，区分聊天室、普通消息
            if (this.type === "session") {
                // if (item.flow === "in") {
                if (item.type !== "timeTag") {
                    if (item.from !== this.$store.state.userUID) {
                        // console.log(this.$store.state.userInfos[item.from]);
                        if (
                            !this.$store.state.userInfos[item.from] ||
                            !this.$store.state.userInfos[item.from].public
                        ) {
                            item.avatar = config.defaultUserIcon;
                        } else {
                            item.avatar = util.makeImageUrl(
                                this.$store.state.userInfos[item.from].public
                                    ? this.$store.state.userInfos[item.from]
                                          .public.photo
                                    : null
                            );
                            item.avatar = !item.avatar
                                ? config.defaultUserIcon
                                : item.avatar;
                        }
                    } else {
                        item.avatar = this.myInfo.avatar;
                    }
                }
            }
            // console.log("item.type", !item.type);
            !item.type
                ? item.from === this.$store.state.userUID
                    ? (item.flow = "out")
                    : (item.flow = "in")
                : "";
            if (item.type === "timeTag") {
                // 标记发送的时间
                item.showText = item.text;
            } else if (typeof item.content === "string") {
                // 文本消息
                item.showText = tea.xxtea_decrypt(item.content, config.teaKey);
                // console.log("xxtea_decrypt", item.showText, item.content);
                item.type = "text";
                // item.showText = util.escape(item.text);
                // emoji表情显示
                if (/\[[^\]]+\]/.test(item.showText)) {
                    let emojiItems = item.showText.match(/\[[^\]]+\]/g);
                    emojiItems.forEach(text => {
                        let emojiCnt = emojiObj.emojiList.emoji;
                        if (emojiCnt[text]) {
                            item.showText = item.showText.replace(
                                text,
                                `<img class="emoji-small" src="${emojiCnt[text].img}">`
                            );
                        }
                    });
                }
            } else if (typeof item.content === "object") {
                if (
                    item.content.ent[0].tp === "IM" ||
                    (/^image/.test(item.content.ent[0].data.mime) &&
                        item.content.ent[0].data.val)
                ) {
                    item.type = "image";
                    let photo = {
                        type: /jpeg/.test(item.content.ent[0].data.mime)
                            ? "jpeg"
                            : /png/.test(item.content.ent[0].data.mime)
                            ? "png"
                            : /jpg/.test(item.content.ent[0].data.mime)
                            ? "jpg"
                            : "gif",
                        data: item.content.ent[0].data.val
                    };
                    console.log(Drafty.getPreviewUrl(item.content.ent[0].data));
                    item.originLink = util.makeImageUrl(photo)
                        ? util.makeImageUrl(photo)
                        : Drafty.getPreviewUrl(item.content.ent[0].data); //192.168.31.67:6060/v0/channels?apikey=AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K
                    console.log(
                        Drafty.getDownloadUrl(item.content.ent[0].data)
                    );
                    console.log(
                        Drafty.getEntityMimeType(item.content.ent[0].data)
                    );
                    console.log(Drafty.getEntitySize(item.content.ent[0].data));
                } else {
                    item.type = "file";
                    item.fileLink = item.content.ent[0].data.val;
                    item.showText = item.content.ent[0].data.name;
                }
            } else if (item.type === "image") {
                // 原始图片全屏显示
                item.originLink = item.file.url;
            } else if (item.type === "video") {
                // ...
            } else if (item.type === "audio") {
                item.width =
                    (5.3 + Math.round(item.file.dur / 1000) * 0.03).toFixed(2) +
                    "rem";
                item.audioSrc = item.file.mp3Url;
                item.showText =
                    "<i>" + Math.round(item.file.dur / 1000) + '"</i> 点击播放';
                if (!this.isHistory && this.$store.state.nim.useDb) {
                    item.unreadAudio = !item.localCustom;
                }
            } else if (item.type === "file") {
                item.fileLink = item.file.url;
                item.showText = item.file.name;
            } else if (item.type === "notification") {
                if (item.scene === "team") {
                    item.showText = util.generateTeamSysmMsg(item);
                } else {
                    //对于系统通知，更新下用户信息的状态
                    item.showText = util.generateChatroomSysMsg(item);
                }
            } else if (item.type === "tip") {
                //对于系统通知，更新下用户信息的状态
                item.showText = item.tip;
            } else if (item.type === "robot") {
                let content = item.content || {};
                let message = content.message || [];
                if (!content.msgOut) {
                    // 机器人上行消息
                    item.robotFlow = "out";
                    item.showText = item.text;
                } else if (content.flag === "bot") {
                    item.subType = "bot";
                    message = message.map(item => {
                        if (item.type === "template") {
                            // 在vuex(store/actions/msgs.js)中已调用sdk方法做了转换
                            return item.content.json;
                        } else if (
                            item.type === "text" ||
                            item.type === "answer"
                        ) {
                            // 保持跟template结构一致
                            return [
                                {
                                    type: "text",
                                    text: item.content
                                }
                            ];
                        } else if (item.type === "image") {
                            // 保持跟template结构一致
                            return [
                                {
                                    type: "image",
                                    url: item.content
                                }
                            ];
                        }
                    });
                    item.message = message;
                } else if (item.content.flag === "faq") {
                    item.subType = "faq";
                    item.query = message.query;
                    let match = message.match.sort((a, b) => {
                        // 返回最匹配的答案
                        return b.score - a.score;
                    });
                    item.message = match[0];
                }
            } else {
                item.showText = `[${util.mapMsgType(
                    item
                )}],请到手机或电脑客户端查看`;
            }
            // console.log(item);
            this.msg = item;
        }
    },
    components: {}
};
</script>
<style>
</style>
<style scoped lang="less">
.chat_item {
    margin-top: 20px;
    .tip {
        display: inline-block;
        padding: 4px;
        box-sizing: border-box;
        background: #ddd;
        color: #fff;
        border-radius: 4px;
    }
    .avatar {
        width: 40px;
        height: 40px;
        background: #ddd;
        margin-right: 11px;
        // margin-right: px;
    }
    .avatar_right {
        margin-left: 21px;
        margin-right: 0;
    }
    .txt_info {
        background: #fff;
        padding: 10px 15px;
        border-radius: 4px;
        box-sizing: border-box;
        margin-left: 10px;
        position: relative;
        max-width: 240px;
        word-break: break-all;
        text-align: left;
        font-size: 14px;
        .triangle {
            position: absolute;
            top: 14px;
        }
        .triangle_left {
            left: -8px;
            width: 0;
            height: 0;
            border-top: 4px solid transparent;
            border-right: 8px solid #fff;
            border-bottom: 4px solid transparent;
        }
        .triangle_right {
            right: -8px;
            width: 0;
            height: 0;
            border-top: 4px solid transparent;
            border-left: 8px solid #2396f7;
            border-bottom: 4px solid transparent;
        }
    }
}
</style>
